package com.bobi.tfca.ui.member

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class MemberListFragmentVM: ViewModel() {

    val members by lazy {
        MutableLiveData(ArrayList<MemberResponse>())
    }

    /**
     * 查询群成员
     */
    fun findAllGroupMembers(
        publicViewModel: PublicViewModel,
        groupId: Int,
        fragment: MemberListFragment
    ) {
        publicViewModel.apply {
            request(MessageAPI::class.java).findAllGroupMembers(groupId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                // 赋值
                                var result = it.data!!.data
                                if (result != null) {
                                    members.value = result as ArrayList<MemberResponse>
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}